
from .utils.redis_task import TaskRedisManager

from rest_framework.views import APIView
from rest_framework.response import Response
from job.utils import resume_tool
from home.models import Jobposting
from django.http import JsonResponse
from celery.result import AsyncResult
from user.models import JobInfo, HRInfo, User
from home.homeser import JobpostingSer
from django.core.exceptions import ObjectDoesNotExist
from job.jobser import DeliverJobpostingSer, DeliverJobSer, InterviewSerializer



# 获取hr发布的所有职位
class HRJobListView(APIView):
    def get(self, request):
        user_id = int(request.query_params.get('user_id'))
        try:
            user = User.objects.get(id=user_id)
            hr = HRInfo.objects.get(user=user)
            jobs = Jobposting.objects.filter(hr_id=hr.id)
            print(f"Jobs found: {jobs}")
            jobs_ser = JobpostingSer(jobs, many=True)
            return JsonResponse({"code": 200, "msg": "获取成功", "data": jobs_ser.data})
        except ObjectDoesNotExist:
            return JsonResponse({"code": 404, "msg": "用户或HR不存在"}, status=404)


#  获取某职位下所有投递简历（含简历url、求职者信息）
class JobDataView(APIView):
    def get(self, request):
        job_id = int(request.query_params.get('job_id'))
        delivers = DeliverJobposting.objects.filter(jobposting_id=job_id)
        job_data = DeliverJobpostingSer(delivers, many=True)
        return JsonResponse({"code": 200, "msg": "获取成功", "data": job_data.data})


# hr发起ai海选 批量处理 （批量分发简历处理任务）
class AIScreeningView(APIView):
    def post(self, request):
        job_id = int(request.data.get('job_id'))
        # 1. 获取所有投递该职位的简历ID
        resume_ids = list(DeliverJobposting.objects.filter(jobposting_id=job_id).values_list('jobinfo_id', flat=True))
        # 2. 批量派发Celery任务
        task_ids = []
        for rid in resume_ids:
            # 1. 分发Celery任务
            task = resume_tool.process_resumes.delay(job_id, rid)
            task_ids.append({"resume_id": rid, "task_id": task.id})
        return Response(
            {"tasks": task_ids, "msg": f"AI海选任务已启动,成功发起{len(resume_ids)}个简历处理任务", "code": 200, })


# 调用工具类（如 redis_task.py）的 TaskRedisManager，先查 Redis 拿 task_id，再查 Celery result backend 拿状态和结果。
class TaskQueryView(APIView):
    def get(self, request):
        # 获取请求参数：简历id 职位id
        resume_id = request.query_params.get('resume_id', "")
        job_id = request.query_params.get('job_id', "")

        if not all([resume_id, job_id]):
            return Response(
                {"error": "需提供 resume_id、job_id、task_type 参数"},
                status=400
            )

        # 1. 从 Redis 查询任务元信息
        task_meta = TaskRedisManager.get_task_meta(
            resume_id=int(resume_id),
            job_id=int(job_id)
        )
        if not task_meta:
            return Response({"error": "未找到任务"}, status=404)

        # 2. 从 Celery 结果后端查询详细结果
        task_result = AsyncResult(task_meta["task_id"])
        result_data = task_result.result if task_meta["status"] == "SUCCESS" else None

        # 3. 补充初筛结果（若成功）
        screening_result = None
        if task_meta["status"] == "SUCCESS":
            try:
                interview = Interview.objects.get(
                    deliverjob__jobposting_id=job_id,
                    deliverjob__jobinfo_id=resume_id
                )
                screening_result = {
                    "ai_match_score": interview.ai_match_score,
                    "match_points": interview.ai_match_points,
                    "risk_points": interview.ai_risk_points,
                    "hr_evaluation": interview.hr_evaluation,
                    "user_evaluation": interview.user_evaluation,
                    "passed": interview.ai_search_score >= 0.5  # 初筛通过判断
                }
            except Interview.DoesNotExist:
                screening_result = None

        return Response({
            "code": 200,
            "data": {
                "resume_id": resume_id,
                "job_id": job_id,
                "task_id": task_meta["task_id"],
                "task_status": task_meta["status"],
                "screening_result": screening_result,  # 初筛结果-结构化
                "error": str(task_result.result) if task_meta["status"] == "FAILURE" else None
            }
        })


class PassedResumesView(APIView):
    def get(self, request):
        try:
            job_id = int(request.query_params.get('job_id'))
        except (TypeError, ValueError):
            return JsonResponse({"code": 400, "msg": "job_id 参数无效"})
        # 根据投递信息获取面试信息
        deliver_jobs = DeliverJobposting.objects.filter(jobposting_id=job_id)
        interview_results = Interview.objects.filter(deliverjob__in=deliver_jobs)
        inter_ser=InterviewSerializer(interview_results, many=True)
        return JsonResponse({"code": 200, "msg": "获取成功", "data": inter_ser.data})


from rest_framework.views import APIView
from rest_framework.response import Response
from job.models import Interview
from user.models import User, HRInfo
from home.models import DeliverJobposting


class ScreeningResultView(APIView):
    """HR查看职位下通过的简历；求职者查看个人结果"""

    def get(self, request):
        # 1. 获取当前登录用户，判断身份（HR/求职者）
        # # 前端在发送请求时，需要携带用户的认证信息，通常是通过 HTTP 头中的 Authorization 字段传递 Token。
        # user = request.user  # DRF中通过Token/会话获取用户

        userid = request.query_params.get('user_id')
        user = User.objects.get(id=userid)
        is_hr = False
        try:
            # 检查是否存在HR身份关联（假设HRInfo是HR的扩展模型）
            HRInfo.objects.get(user=user)
            is_hr = True
        except HRInfo.DoesNotExist:
            is_hr = False

            # 2. 根据身份分支处理
            if is_hr:
                # HR逻辑：需传入job_id，返回该职位下所有通过初筛的简历
                job_id = request.query_params.get('job_id')
                resume_id = request.query_params.get('resume_id')  # 新增：获取简历ID

                if not job_id:
                    return Response({"error": "HR需提供job_id"}, status=400)

                # 3. 查询通过初筛的简历
                if resume_id:  # 如果提供了简历ID
                    try:
                        interview = Interview.objects.filter(
                            deliverjob__jobposting_id=job_id,  # 关联职位ID
                            deliverjob__jobinfo_id=resume_id  # 个人简历ID
                        ).first()
                        result = {
                            "resume_id": interview.deliverjob.jobinfo.id,  # 求职者简历ID
                            "candidate_name": interview.deliverjob.jobinfo.name,  # 求职者姓名
                            "ai_search_score": interview.ai_search_score,  # 检索评分
                            "match_points": interview.ai_match_points,  # 匹配点
                            "hr_evaluation": interview.hr_evaluation,  # LLM生成的HR分析
                            "processed_at": interview.end_at.strftime("%Y-%m-%d %H:%M")  # 处理时间
                        }
                        return Response({"code": 200, "data": result})
                    except Interview.DoesNotExist:
                        return Response({"code": 400, "error": "未找到该简历的面试记录"}, status=404)
                else:  # 如果没有提供简历ID，默认获取该职位下所有求职者面试的hr分析报告
                    interviews = Interview.objects.filter(
                        deliverjob__jobposting_id=job_id,  # 关联职位ID
                    ).select_related('deliverjob__jobinfo')  # 联表查询简历信息

                    # 4. 构造HR视角的结果列表
                    result = []
                    for interview in interviews:
                        deliver = interview.deliverjob  # 简历投递记录
                        result.append({
                            "resume_id": deliver.jobinfo.id,  # 求职者简历ID
                            "candidate_name": deliver.jobinfo.name,  # 求职者姓名
                            "ai_search_score": interview.ai_search_score,  # 检索评分
                            "match_points": interview.ai_match_points,  # 匹配点
                            "hr_evaluation": interview.hr_evaluation,  # LLM生成的HR分析
                            "processed_at": interview.end_at.strftime("%Y-%m-%d %H:%M")  # 处理时间
                        })
                    return Response({"code": 200, "data": result})

        else:
            # 求职者逻辑：需传入resume_id + job_id，返回个人结果
            resume_id = request.query_params.get('resume_id')
            job_id = request.query_params.get('job_id')
            if not (resume_id and job_id):
                return Response({"error": "求职者需提供resume_id和job_id"}, status=400)

            # 5. 查询个人初筛结果
            try:
                interview = Interview.objects.filter(
                    deliverjob__jobposting_id=job_id,  # 职位ID
                    deliverjob__jobinfo_id=resume_id  # 个人简历ID
                ).first()
                # 6. 构造求职者视角的结果
                return Response({
                    "code": 200,
                    "data": {
                        "resume_id": resume_id,
                        "ai_match_score": interview.ai_match_score,  # 综合评分
                        "match_points": interview.ai_match_points,  # 优势
                        "risk_points": interview.ai_risk_points,  # 劣势
                        "user_evaluation": interview.user_evaluation,  # LLM生成的建议
                        "passed": interview.ai_search_score >= 0.5  # 是否通过
                    }
                })
            except Interview.DoesNotExist:
                return Response({"code": 200, "error": "未找到初筛结果"}, status=404)


from rest_framework import status


class MyDeliveriesView(APIView):
    def get(self, request):
        user_id = request.query_params.get('user_id')  # 获取前端传的 user_id
        if not user_id:
            return Response({"code": 400, "msg": "缺少 user_id 参数"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(id=user_id)
            jobinfo = JobInfo.objects.filter(user=user).first()
            # # 通过用户关联的简历，找到投递记录（这里根据实际模型关联关系调整，比如简历 -> 投递记录）
            deliveries = DeliverJobposting.objects.filter(jobinfo=jobinfo).select_related(
                'jobposting', 'jobposting__company'  # 连表查询优化，减少数据库查询次数
            )
            deliveries_ser=DeliverJobSer(deliveries, many=True)
            # deliveries_ser=DeliverJobpostingSer(deliveries, many=True)

            return Response({"code": 200, "data": deliveries_ser.data}, status=status.HTTP_200_OK)
            # return Response({"code": 200, "data": deliveries}, status=status.HTTP_200_OK)
        except User.DoesNotExist:
            return Response({"code": 404, "msg": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({"code": 500, "msg": f"服务器内部错误：{str(e)}"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
